#include"comm.h"
#include<string.h>
#include<stdlib.h> //exit
#include<sys/types.h>
#include<sys/wait.h> //waitpid

int main()
{
  if(mkfifo(MY_FIFO, 0666)<0)
  {
    perror("mkfifo");
    return 1;
  }
  
  /*只需要文件操作即可*/
  int fd = open(MY_FIFO, O_RDONLY);
  if(fd < 0)
  {
    perror("open");
    return 2;
  }
  
  //业务逻辑，可以进行对应的读写了
  while(1)
  {
    char buffer[64] = {0};
    sleep(50);
    ssize_t s = read(fd, buffer, sizeof(buffer)-1);
    if(s > 0)
    {
      //success
      buffer[s] = 0; //当做字符串儿，并覆盖读入的'\n'
      if(strcmp(buffer, "show") == 0)
      {
        if(fork() == 0)
        {
          execl("/usr/bin/ls", "ls", "-l", NULL);
          exit(1);
        }
        waitpid(-1, NULL, 0);
      }
      else if(strcmp(buffer, "wait for me") == 0)
      {
        if(fork() == 0)
        {
          execl("/usr/bin/sl", "sl", NULL);
          exit(1);
        }
        waitpid(-1, NULL, 0);
      }
      else 
      {
        printf("client# %s\n", buffer);
      }
    }
    else if(s == 0)
    {
      //peer close...
      printf("client quit...\n");
      break;
    }
    else 
    {
      //error
      perror("read");
      break; 
    }
  }

  close(fd);
  return 0;
}
